import hashlib
import re
import time

import requests

headers = {
	'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
	'Accept-Encoding': 'gzip, deflate, br',
	'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
	'Cache-Control': 'no-cache',
	'Connection': 'keep-alive',
	'Cookie': 'HMF_CI=0436db3cc8fb7cc087417a84b69c2dbb1a26172fa55b833cfd055261db71a437629f4e806902498abb3973c87782b6241f7bc2e3140caffd1290ff00c342d58894; cna=usDFG0ZYIkECAXMsbEnssO/E; sca=24567c9d; HMY_JC=02e9975e876697a3eb07e8cddabed230b80598939f917b0be908c3a9ef9554036c,; HBB_HC=678e20df8fe58f2de515dac177df384c5e4f7c1d61d57335c695f1c2fbf95fd5197487cde3e83352b865b0b82cbd904afb; atpsida=fb561904c7646dc6fea45a99_1704867185_460',
	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
}


def resolveurl(src_url):
	ret = requests.get(src_url, headers=headers)
	html = ret.text
	# print(html)
	pattern = re.compile('guid_Ad_VideoCode = "(.+?)";')
	guid = re.findall(pattern, html).pop()
	# print(guid)
	tsp = int(time.time())
	checker = '47899B86370B879139C08EA3B5E88267'
	uid = 'CC480EB341F3B756F0FAB96702E55BA5'
	vc = f'{tsp}2049{checker}{uid}'
	md5 = hashlib.md5(vc.encode())
	vc = md5.hexdigest().upper()
	# path = f'https://vdn.apps.cntv.cn/api/getHttpVideoInfo.do?pid={guid}&client=flash&im=0&tsp={tsp}&vn=2049&vc={vc}&uid={uid}&wlan='
	path = 'https://vdn.apps.cntv.cn/api/getHttpVideoInfo.do'
	ret = requests.get(path, {
		'pid': guid,
		'client': 'flash',
		'im': 0,
		'tsp': tsp,
		'vn': 2049,
		'vc': vc,
		'uid': uid,
		'wlan': ''
	})
	rjson = ret.json()
	return rjson['hls_url']


if __name__ == '__main__':
	rfile = open('../resources/wlq_qg.txt', encoding='utf-8')
	wfile = open('../resources/wlq_qg.m3u8', 'w', encoding='utf-8')
	wfile.write('#EXTM3U\n')
	for line in rfile:
		url, title = line.strip().split('|')
		print(url, title)
		m3u8 = resolveurl(url)
		wfile.writelines(f'#EXTINF:-1,{title}\n{m3u8}\n')
